package parser

import (
	"learngo/crawler/config"
	"learngo/crawler/engine"
	"learngo/crawler/model"
	"regexp"
)

var genderRe = regexp.MustCompile(`"genderString":"([^"]+)",`)
var basicRe = regexp.MustCompile(`"basicInfo":\["([^"]+)","([^"]+)","([^"]+)","([^"]+)","([^"]+)","([^"]+)","([^"]+)","([^"]+)","([^"]+)"\],`)
var idUrlRe = regexp.MustCompile(
	`http://album.zhenai.com/u/([\d]+)`)
var guessRe = regexp.MustCompile(
	`<a class="exp-user-name"[^>]*href="(http://album.zhenai.com/u/[\d]+)">([^<]+)</a>`)

func parseProfile(contents []byte,  url string, name string) engine.ParserResult{
	profile := model.Profile{}
	profile.Name = name;

	m := basicRe.FindSubmatch(contents)
	g := genderRe.FindSubmatch(contents)

	if len(m) >0 {
		profile.Marriage = string(m[1])
		profile.Age = string(m[2])
		profile.Xinzuo= string(m[3])
		profile.Height = string(m[4])
		profile.Weight = string(m[5])
		profile.Hokou = string(m[6])
		profile.Income= string(m[7])
		profile.Occupation= string(m[8])
		profile.Education= string(m[9])
	}
	if len(g) >0 {
		profile.Gender = string(g[1])
	}

	result := engine.ParserResult{
		Items: []engine.Item{
			{
				Url:  url,
				Type: "zhenai",
				Id: extractString([]byte(url), idUrlRe),
				Payload: profile,
			},
		},
	}
	//matches := guessRe.FindAllSubmatch(
	//	contents, -1)
	//for _, m := range matches {
	//	result.Requests = append(result.Requests,
	//		engine.Request{
	//			Url: string(m[1]),
	//			Parser: NewProfileParser(
	//				string(m[2])),
	//		})
	//}

	return result

}
func extractString(contents []byte, re *regexp.Regexp) string {
	match := re.FindSubmatch(contents)

	if len(match) >= 2 {
		return string(match[1])
	} else {
		return ""
	}
}

type ProfileParser struct {
	userName string
}

func (p *ProfileParser) Parse(
	contents []byte,
	url string) engine.ParserResult {
	return parseProfile(contents, url, p.userName)
}

func (p *ProfileParser) Serialize() (
	name string, args interface{}) {
	return config.ParseProfile, p.userName
}

func NewProfileParser(name string) *ProfileParser {
	return &ProfileParser{
		userName: name,
	}
}
